<template>
  <div class="categories-management">
    <!-- 页面标题和操作栏 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h2 class="page-title mb-1">版块管理</h2>
        <p class="text-muted mb-0">管理信息分类版块，支持查看、编辑、删除等操作</p>
      </div>
      <div class="d-flex gap-2">
        <button class="btn btn-primary" @click="showAddCategoryModal">
          <i class="bi bi-plus-circle me-2"></i>添加版块
        </button>
      </div>
    </div>

    <!-- 版块列表 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">版块列表</h5>
        <div class="d-flex align-items-center gap-2">
          <span class="text-muted small">共 {{ categories.length }} 个版块</span>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th width="50">ID</th>
                <th>版块名称</th>
                <th>版块描述</th>
                <th width="80">图标</th>
                <th>排序</th>
                <th>状态</th>
                <th>创建时间</th>
                <th width="120">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="category in categories" :key="category.id">
                <td>{{ category.id }}</td>
                <td>
                  <strong class="text-primary">{{ category.name }}</strong>
                </td>
                <td>
                  <span class="text-muted">{{ category.description || '暂无描述' }}</span>
                </td>
                <td>
                  <i v-if="category.icon" :class="category.icon" style="font-size: 1.5rem;"></i>
                  <span v-else class="text-muted">无图标</span>
                </td>
                <td>{{ category.sortOrder }}</td>
                <td>
                  <span class="badge" :class="category.status === 'active' ? 'bg-success' : 'bg-secondary'">
                    {{ category.status === 'active' ? '启用' : '停用' }}
                  </span>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <small class="text-muted">{{ formatDate(category.createdAt) }}</small>
                  </div>
                </td>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button 
                      class="btn btn-outline-primary"
                      @click="editCategory(category)"
                      title="编辑"
                    >
                      <i class="bi bi-pencil"></i>
                    </button>
                    <button 
                      class="btn" 
                      :class="category.status === 'active' ? 'btn-outline-warning' : 'btn-outline-success'"
                      @click="toggleCategoryStatus(category)"
                      :title="category.status === 'active' ? '停用版块' : '启用版块'"
                    >
                      <i class="bi" :class="category.status === 'active' ? 'bi-eye-slash' : 'bi-eye'"></i>
                    </button>
                    <button 
                      class="btn btn-outline-danger"
                      @click="deleteCategory(category)"
                      title="删除"
                    >
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空状态 -->
        <div v-if="categories.length === 0" class="text-center py-5">
          <i class="bi bi-tags display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无版块数据</p>
        </div>
      </div>
    </div>

    <!-- 添加/编辑版块模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="categoryModalLabel">{{ isEditing ? '编辑版块' : '添加版块' }}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <form>
              <div class="mb-3">
                <label for="name" class="form-label">版块名称</label>
                <input type="text" class="form-control" id="name" v-model="currentCategory.name" required>
              </div>
              
              <div class="mb-3">
                <label for="description" class="form-label">版块描述</label>
                <textarea class="form-control" id="description" v-model="currentCategory.description" rows="3"></textarea>
              </div>
              
              <div class="mb-3">
                <label for="icon" class="form-label">图标 </label>
                <input type="text" class="form-control" id="icon" v-model="currentCategory.icon" placeholder="例如: SVG代码">
                <div class="form-text">使用 阿里巴巴矢量图 SVG代码名，参考 <a href="https://www.iconfont.cn/" target="_blank">阿里巴巴矢量图</a></div>
              </div>
              
              <div class="mb-3">
                <label for="sortOrder" class="form-label">排序</label>
                <input type="number" class="form-control" id="sortOrder" v-model="currentCategory.sortOrder">
              </div>
              
              <div class="mb-3">
                <label for="status" class="form-label">状态</label>
                <select class="form-select" id="status" v-model="currentCategory.status">
                  <option value="active">启用</option>
                  <option value="inactive">停用</option>
                </select>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="saveCategory">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCategoriesService, 
  addCategoryService, 
  updateCategoryService, 
  deleteCategoryService, 
  updateCategoryStatusService 
} from '@/api/categories.js'

// 引入Bootstrap的Modal组件
import { Modal } from 'bootstrap'

// 响应式数据
const categories = ref([])
const isEditing = ref(false)
const currentCategory = reactive({
  id: null,
  name: '',
  description: '',
  icon: '',
  sortOrder: 0,
  status: 'active'
})

// 方法
const loadCategories = async () => {
  try {
    const response = await getCategoriesService()
    if (response.code === 0) {
      categories.value = response.data
    } else {
      ElMessage.error('获取版块列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取版块列表失败: ' + error.message)
  }
}

const showAddCategoryModal = () => {
  // 重置表单
  isEditing.value = false
  currentCategory.id = null
  currentCategory.name = ''
  currentCategory.description = ''
  currentCategory.icon = ''
  currentCategory.sortOrder = 0
  currentCategory.status = 'active'
  
  // 显示模态框
  const categoryModal = new Modal(document.getElementById('categoryModal'))
  categoryModal.show()
}

const editCategory = (category) => {
  // 设置编辑状态
  isEditing.value = true
  // 填充表单数据
  currentCategory.id = category.id
  currentCategory.name = category.name
  currentCategory.description = category.description
  currentCategory.icon = category.icon
  currentCategory.sortOrder = category.sortOrder
  currentCategory.status = category.status
  
  // 显示模态框
  const categoryModal = new Modal(document.getElementById('categoryModal'))
  categoryModal.show()
}

const saveCategory = async () => {
  try {
    let response
    if (isEditing.value) {
      // 更新版块
      response = await updateCategoryService(currentCategory)
    } else {
      // 添加版块
      response = await addCategoryService(currentCategory)
    }
    
    if (response.code === 0) {
      await loadCategories()
      // 关闭模态框
      const categoryModalEl = document.getElementById('categoryModal')
      const categoryModal = Modal.getInstance(categoryModalEl) || new Modal(categoryModalEl)
      categoryModal.hide()
      ElMessage.success(isEditing.value ? '版块更新成功' : '版块添加成功')
    } else {
      ElMessage.error(isEditing.value ? '版块更新失败: ' + response.msg : '版块添加失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error(isEditing.value ? '版块更新失败: ' + error.message : '版块添加失败: ' + error.message)
  }
}

const toggleCategoryStatus = async (category) => {
  try {
    const newStatus = category.status === 'active' ? 'inactive' : 'active'
    const response = await updateCategoryStatusService(category.id, newStatus)
    
    if (response.code === 0) {
      category.status = newStatus
      ElMessage.success(newStatus === 'active' ? '版块已启用' : '版块已停用')
    } else {
      ElMessage.error('更新版块状态失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('更新版块状态失败: ' + error.message)
  }
}

const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除版块 "${category.name}" 吗？此操作不可逆！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteCategoryService(category.id)
    if (response.code === 0) {
      await loadCategories()
      ElMessage.success('版块删除成功')
    } else {
      ElMessage.error('删除版块失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除版块失败: ' + error.message)
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.page-title {
  color: #2c3e50;
  font-weight: 600;
}

.table th {
  border-top: none;
  font-weight: 600;
  color: #6c757d;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.table-hover > tbody > tr:hover > td {
  background-color: #e3f2fd !important;
}

.table > tbody > tr {
  transition: background-color 0.2s ease;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-responsive {
    font-size: 0.875rem;
  }
  
  .btn-group-sm > .btn {
    padding: 0.25rem 0.5rem;
  }
}
</style>